package com.pig4cloud.pig.module.controller.farm;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.farm.FarmAdopt;
import com.pig4cloud.pig.module.api.entity.farm.FarmAdoptImg;
import com.pig4cloud.pig.module.service.farm.IFarmAdoptImgService;
import com.pig4cloud.pig.module.service.farm.IFarmAdoptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 领养中心Controller
 *
 * @author ruoyi
 * @date 2021-12-29
 */
@Validated
@Api(value = "领养中心控制器", tags = {"领养中心管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/farm/adopt")
public class FarmAdoptController {

    private final IFarmAdoptService farmAdoptService;
    private final IFarmAdoptImgService farmAdoptImgService;
    @Value("${ruoyi.imgUrl}")
    private String imgUrl;
    /**
     * 查询领养中心列表
     */
    @ApiOperation("查询领养中心列表")
    @PreAuthorize("@pms.hasPermission('module:adopt:list')")
    @GetMapping("/list")
    public TableDataInfo<FarmAdopt> list(@Validated FarmAdopt farmAdopt) {
        QueryWrapper<FarmAdopt> qw = new QueryWrapper<>();
        if(farmAdopt.getMerId()!=null){
            qw.eq("mer_id",farmAdopt.getMerId());
        }
        TableDataInfo<FarmAdopt> td = PageUtils.buildDataInfo(farmAdoptService.page(PageUtils.buildPage(),qw));
        List<FarmAdopt> list = td.getData();
        return td;
    }

    /**
     * 获取领养中心详细信息
     */
    /*@ApiOperation("获取领养中心详细信息")
    @PreAuthorize("@pms.hasPermission('system:adopt:query')")
    @GetMapping("/{id}")
    public R<FarmAdopt> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        FarmAdopt farmAdopt = farmAdoptService.getById(id);
        return R.ok(farmAdopt);
    }
*/


    @ApiOperation("获取领养中心详细信息")
    @PreAuthorize("@pms.hasPermission('module:adopt:query')")
    @GetMapping("/{id}")
    public R<FarmAdopt> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        FarmAdopt farmAdopt = farmAdoptService.getById(id);
        String lunboImgs = "";
        QueryWrapper<FarmAdoptImg> qw = new QueryWrapper<>();
        qw.eq("adopt_id",id);
        qw.eq("file_type","png");
        List<FarmAdoptImg> lunbos = farmAdoptImgService.list(qw);
        System.out.println(lunbos);
        for (FarmAdoptImg img : lunbos){
            if(StrUtil.isNotEmpty(img.getImgUrl())) {
                lunboImgs += imgUrl + img.getImgUrl() + ",";
                img.setImgUrl(imgUrl + img.getImgUrl());
                System.out.println(lunboImgs);
            }
        }

        farmAdopt.setAdoptImgs(lunbos);
        if(StrUtil.isNotEmpty(lunboImgs)){
            lunboImgs = lunboImgs.substring(0,lunboImgs.length() - 1);
            System.out.println(lunboImgs);
        }
        farmAdopt.setAdoptImg(lunboImgs);

        String videos = "";
        QueryWrapper<FarmAdoptImg> qw1 = new QueryWrapper<>();
        qw.eq("adopt_id",id);
        qw.eq("file_type","mp4");
        List<FarmAdoptImg> video = farmAdoptImgService.list(qw1);
        for (FarmAdoptImg img : video){
            if(StrUtil.isNotEmpty(img.getImgUrl())) {
                videos += imgUrl + img.getImgUrl() + ",";
                img.setImgUrl(imgUrl + img.getImgUrl());
            }
        }
        farmAdopt.setAdoptVideos(video);
        if(StrUtil.isNotEmpty(videos)){
            videos = videos.substring(0,videos.length() - 1);
        }
        farmAdopt.setAdoptVideo(videos);
        return R.ok(farmAdopt);
    }

    /**
     * 新增领养中心
     */
    @ApiOperation("新增领养中心")
    @PreAuthorize("@pms.hasPermission('module:adopt:add')")
    @SysLog("领养中心")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody FarmAdopt farmAdopt) {
        boolean bl = farmAdoptService.save(farmAdopt);
        if(bl){
            List<FarmAdoptImg> delImg = new ArrayList<>();

            List<FarmAdoptImg> imgs = farmAdopt.getAdoptImgs();
            List<FarmAdoptImg> videos = farmAdopt.getAdoptVideos();

            QueryWrapper<FarmAdoptImg> qw = new QueryWrapper<>();
            qw.eq("adopt_id",farmAdopt.getId());
            /*qw.eq("file_type","png");*/
            List<FarmAdoptImg> infoImgs = farmAdoptImgService.list(qw);
            if(CollUtil.isNotEmpty(infoImgs)){
                for (FarmAdoptImg img : infoImgs){
                    int isHas = 0;
                    for (FarmAdoptImg img1 : imgs){
                        if(img1.getId()!=null && img.getImgUrl().equals(img1.getImgUrl())){//存在
                            isHas = 1;
                        }
                    }
                    for (FarmAdoptImg img2 : videos){
                        if(img2.getId()!=null && img.getImgUrl().equals(img2.getImgUrl())){//存在
                            isHas = 1;
                        }
                    }
                    if(isHas == 0){
                        delImg.add(img);
                    }
                }
            }
            if(CollUtil.isNotEmpty(videos)){
                for (FarmAdoptImg img : videos){
                    if(img.getId() == null){
                        img.setAdoptId(farmAdopt.getId());
                        img.setSort(1L);
                        img.setFileType("mp4");
                        farmAdoptImgService.save(img);
                    }
                }
            }
            if(CollUtil.isNotEmpty(imgs)){
                for (FarmAdoptImg img : imgs){
                    if(img.getId() == null){
                        img.setAdoptId(farmAdopt.getId());
                        img.setSort(1L);
                        img.setFileType("png");
                        farmAdoptImgService.save(img);
                    }
                }
            }
            if(CollUtil.isNotEmpty(delImg)){
                for (FarmAdoptImg img : delImg){
                    farmAdoptImgService.removeById(img.getId());
                }
            }
        }
        return R.okByRow(bl? 1 : 0);
    }

    /**
     * 修改领养中心
     */
    /*@ApiOperation("修改领养中心")
    @PreAuthorize("@pms.hasPermission('system:adopt:edit')")
    @SysLog("领养中心")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody FarmAdopt farmAdopt) {
        return R.okByRow(farmAdoptService.updateById(farmAdopt) ? 1 : 0);
    }*/




    @ApiOperation("修改领养中心")
    @PreAuthorize("@pms.hasPermission('module:adopt:edit')")
    @SysLog("领养中心")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody FarmAdopt farmAdopt) {
        if(farmAdopt.getImgUrl()==null||farmAdopt.getImgUrl()==""){
            farmAdopt.setImgUrl("0");
        }
        if(farmAdopt.getVideoUrl()==null||farmAdopt.getVideoUrl()==""){
            farmAdopt.setVideoUrl("0");
        }
        boolean bl = farmAdoptService.updateById(farmAdopt);
        if(bl){
            List<FarmAdoptImg> delImg = new ArrayList<>();

            List<FarmAdoptImg> imgs = farmAdopt.getAdoptImgs();
            List<FarmAdoptImg> videos = farmAdopt.getAdoptVideos();

            QueryWrapper<FarmAdoptImg> qw = new QueryWrapper<>();
            qw.eq("adopt_id",farmAdopt.getId());
            /*qw.eq("file_type","png");*/
            List<FarmAdoptImg> infoImgs = farmAdoptImgService.list(qw);
            if(CollUtil.isNotEmpty(infoImgs)){
                for (FarmAdoptImg img : infoImgs){
                    int isHas = 0;
                    for (FarmAdoptImg img1 : imgs){
                        if(img1.getId()!=null && img.getImgUrl().equals(img1.getImgUrl())){//存在
                            isHas = 1;
                        }
                    }
                    for (FarmAdoptImg img2 : videos){
                        if(img2.getId()!=null && img.getImgUrl().equals(img2.getImgUrl())){//存在
                            isHas = 1;
                        }
                    }
                    if(isHas == 0){
                        delImg.add(img);
                    }
                }
            }
            if(CollUtil.isNotEmpty(videos)){
                for (FarmAdoptImg img : videos){
                    if(img.getId() == null){
                        img.setAdoptId(farmAdopt.getId());
                        img.setSort(1L);
                        img.setFileType("mp4");
                        farmAdoptImgService.save(img);
                    }
                }
            }
            if(CollUtil.isNotEmpty(imgs)){
                for (FarmAdoptImg img : imgs){
                    if(img.getId() == null){
                        img.setAdoptId(farmAdopt.getId());
                        img.setSort(1L);
                        img.setFileType("png");
                        farmAdoptImgService.save(img);
                    }
                }
            }
            if(CollUtil.isNotEmpty(delImg)){
                for (FarmAdoptImg img : delImg){
                    farmAdoptImgService.removeById(img.getId());
                }
            }
        }
        return R.okByRow(bl? 1 : 0);
    }

    /**
     * 删除领养中心
     */
    @ApiOperation("删除领养中心")
    @PreAuthorize("@pms.hasPermission('module:adopt:remove')")
    @SysLog("领养中心")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(farmAdoptService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
